package cc.wfu.trigger.http;

import cc.wfu.type.trigger.api.dto.JwtTokenRequest;
import cc.wfu.type.trigger.api.dto.VerifyJwtTokenRequest;
import cc.wfu.domain.auth.service.IAuthService;
import cc.wfu.domain.user.model.entity.UserEntity;
import cc.wfu.domain.user.service.IUserService;
import cc.wfu.type.service.JwtAuthService;
import cc.wfu.types.enums.Constants;
import cc.wfu.types.exception.UserServiceException;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @Author: jia-qiang ljq1024.cc
 * @desc:
 * @Date: 2024-05-20-17:00
 */
@Slf4j
@Service
public class UserControllerSupport {

    @Resource
    protected IAuthService authService;
    @Resource
    protected IUserService userService;
    @Resource
    protected JwtAuthService jwtAuthService;


    /**
     * 生成 jwtToken
     * @param jwtTokenRequest 参数
     * @return jwtToken
     */
    protected String genJwtToken(JwtTokenRequest jwtTokenRequest) {
        String jwtToken = jwtAuthService.genJwtToken(jwtTokenRequest);
        if (jwtToken == null) {
            // 不是成功的结果
            throw new UserServiceException(Constants.ResponseError.GEN_JWT_TOKEN_ERROR.getInfo());
        }
        return jwtToken;
    }

    /**
     * 解析 jwtToken
     */
    protected UserEntity verifyEmailWithJwtToken(String jwtToken) {
        String userJsonStr = jwtAuthService.verifyJwtToken(VerifyJwtTokenRequest.builder().jwtToken(jwtToken).build());
        if ( userJsonStr == null) {
            // 不是成功的结果
            throw new UserServiceException(Constants.ResponseError.VERIFY_JWT_TOKEN_ERROR.getInfo());
        }
        return JSON.parseObject(userJsonStr, UserEntity.class);
    }

    /**
     * 发送 MQ 消息，记录登录时间
     * @param email 用户邮箱
     */
    protected void sendLoginMqMessage(String email) {
        userService.sendLoginMqMessage(email);
        log.info("发送 MQ 消息，记录用户 {} 登录时间 - 完成", email);
    }



}
